package com.ze.familyday.familyphotoframe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.umeng.analytics.MobclickAgent;
import com.ze.commontool.CustomDialog;
import com.ze.familyday.familyphotoframe.R;
import com.ze.familydayverpm.adapter.WifiListViewAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WifiLoginActivity extends Activity{
	public final static String TAG = "WifiLoginActivity";
	Context mContext; 
	ListView mWifiListView;
	BaseAdapter	wifiAdapter;
	List<Map<String, Object>> mList;
	View			mBtnRefresh;
	View			mPbLoading;
	boolean 		mIsRefreshing = false;
	WifiManager wifiManager;
	List<ScanResult> mScanResults;
	List<WifiConfiguration> mWifiConfigurations;
	View dialog_wifiView ;
	EditText dialog_etPw;
	ConnectivityManager conMan;
	AlertDialog progressDialog;
	View 			view_progress;
	TextView		tv_progress;
	ImageButton			btn_progress;
	WifiReceiverInWifiActivity receiver;
	public static WifiLoginActivity instance;
	TextView			tv_wifistate;
	View				btn_close;
	int 					connectIndex = -1;
	Toast toast;
	View toastView;
	TextView toastTxt;
	/**
	 * wifi密码输入对话框
	 */
	Dialog wifiInputDialog;
	/**
	 * wifi密码输入对话框按钮
	 */
	Button cancelBtn, okBtn;
	/**
	 * wifi对话框 输入框
	 */
	EditText passwordEt;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wifilogin);
		instance = this;
		mContext = this;
		//设置提示的toast
		toast = Toast.makeText(mContext, "", Toast.LENGTH_LONG);
		toastView = getLayoutInflater().inflate(R.layout.toast_text, null);
		toastTxt = (TextView) toastView.findViewById(R.id.toast_txt);
		mBtnRefresh = findViewById(R.id.wifi_refresh);
		mPbLoading	= findViewById(R.id.wifi_refresh_loading);
		tv_wifistate = (TextView)findViewById(R.id.wifi_state);
		btn_close = findViewById(R.id.wifi_close);
		btn_close.setOnClickListener(buttonOnClickListener);
		mList = new ArrayList<Map<String,Object>>();
		wifiAdapter = new WifiListViewAdapter(this, mList);
		mWifiListView = (ListView) findViewById(R.id.wifi_list);
		mWifiListView.setAdapter(wifiAdapter);
		wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		
		receiver = new WifiReceiverInWifiActivity();
		IntentFilter filter = new IntentFilter();
		//filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		registerReceiver(receiver, filter);
		
		mBtnRefresh.setOnClickListener(buttonOnClickListener);
		mWifiListView.setOnItemClickListener(itemClickListener);
		dialog_wifiView = this.getLayoutInflater().inflate(R.layout.dialog_wifilogin, null);
		dialog_etPw = (EditText) (dialog_wifiView.findViewById(R.id.wifilogin_pw));
		conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		view_progress = getLayoutInflater().inflate(R.layout.define_progress_dialog, null);
		tv_progress = (TextView) view_progress.findViewById(R.id.dpd_tv);
		btn_progress = (ImageButton)view_progress.findViewById(R.id.dpd_btn);
		btn_progress.setOnClickListener( buttonOnClickListener );
		progressDialog = new AlertDialog.Builder(this).setView(view_progress).create();
		progressDialog.setCanceledOnTouchOutside(false);
		
		//初始化wifi密码输入对话框
		if (wifiInputDialog == null) {
			wifiInputDialog = new CustomDialog(mContext, 450, 250, R.layout.wifi_input_dialog, 
					R.style.FullHeightDialog);
			wifiInputDialog.setCanceledOnTouchOutside(false);
			View view = getLayoutInflater().inflate(R.layout.wifi_input_dialog, null);
			cancelBtn = (Button) view.findViewById(R.id.wifi_input_cancel);
			cancelBtn.setOnClickListener(buttonOnClickListener);
			okBtn = (Button) view.findViewById(R.id.wifi_input_ok);
			okBtn.setOnClickListener(buttonOnClickListener);
			passwordEt = (EditText) view.findViewById(R.id.et_wifi_password);
			wifiInputDialog.setContentView(view);
		}
		
		if (  getIntent().getExtras() != null && getIntent().getExtras().getBoolean("reset", false) )
		{
			wifiManager.setWifiEnabled(false);
			//Toast.makeText(this, "正在重置wifi", Toast.LENGTH_LONG).show();
			toastTxt.setText("Resetting Wifi");
			toast.setView(toastView);
			toast.show();
		}else{
			openWifi();
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}
	public void openWifi()
	{
		if ( ! wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}else
		{
			refreshWifiList();
		}
	}
	public void closeWifi()
	{
		if ( wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(false);
		}
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	
	public void ScanWifiThread() {
		mPbLoading.setVisibility(View.VISIBLE);
		mBtnRefresh.setVisibility(View.INVISIBLE);
		mList.clear();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (!wifiManager.isWifiEnabled())
					wifiManager.setWifiEnabled(true);
				boolean scan = wifiManager.startScan();
				int countTime = 0; 
				while (!scan && countTime < 5){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					countTime ++;
					Log.v(TAG, "是否开始扫描的过程时间：" + countTime);
				}
				Log.v(TAG, "扫描时间：" + countTime);
				if (!scan || countTime >= 5){
					//return null;
					handler.sendEmptyMessage(2);
					return;
				}
				mScanResults = wifiManager.getScanResults();
				mWifiConfigurations = wifiManager.getConfiguredNetworks();
//				mScanResults.get(0);
				countTime = 0;
				while (mScanResults == null && countTime < 5){
					mScanResults = wifiManager.getScanResults();
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					countTime ++;
					Log.v(TAG, "扫描结果的过程时间：" + countTime);
				}
				if( mScanResults == null || countTime >= 5)
				{
					//Toast.makeText(WifiLoginActivity.this, "暂时获取不了wifi信号，请重试", Toast.LENGTH_SHORT).show();
					//return null;
					handler.sendEmptyMessage(2);
					return;
				}
				countTime = 0;
				//return "ScanSuccesss!";
				handler.sendEmptyMessage(1);
			}
		}).start();
	}
	
	class ScanWifiTask extends AsyncTask<Object, Object, Object>{

		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mPbLoading.setVisibility(View.VISIBLE);
			mBtnRefresh.setVisibility(View.INVISIBLE);
			mList.clear();
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			if (!wifiManager.isWifiEnabled())
				wifiManager.setWifiEnabled(true);
			boolean scan = wifiManager.startScan();
			int countTime = 0; 
			while (!scan && countTime < 5){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				countTime ++;
				Log.v(TAG, "是否开始扫描的过程时间：" + countTime);
			}
			Log.v(TAG, "扫描时间：" + countTime);
			if (!scan || countTime >= 5){
				return null;
			}
			mScanResults = wifiManager.getScanResults();
			mWifiConfigurations = wifiManager.getConfiguredNetworks();
//			mScanResults.get(0);
			countTime = 0;
			while (mScanResults == null && countTime < 5){
				mScanResults = wifiManager.getScanResults();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				countTime ++;
				Log.v(TAG, "扫描结果的过程时间：" + countTime);
			}
			if( mScanResults == null || countTime >= 5)
			{
				//Toast.makeText(WifiLoginActivity.this, "暂时获取不了wifi信号，请重试", Toast.LENGTH_SHORT).show();
				return null;
			}
			countTime = 0;
			return "ScanSuccesss!";
		}

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result == null){
				//Toast.makeText(WifiLoginActivity.this, "暂时获取不了wifi信号，请重试！", Toast.LENGTH_SHORT).show();
				toastTxt.setText("Try again");
				toast.setView(toastView);
				toast.show();
				return;
			}
			mPbLoading.setVisibility(View.INVISIBLE);
			mBtnRefresh.setVisibility(View.VISIBLE);
			tv_wifistate.setText("");
			mList.clear();
			int size = mScanResults.size();
			HashMap<String, Object> map;
			ScanResult scanResult;
			
			//mList.clear();
			/*String connectSSID = null;
			if( wifiManager.getConnectionInfo() !=null )
			{
				connectSSID = wifiManager.getConnectionInfo().getSSID();
			}*/
			WifiInfo connectInfo = wifiManager.getConnectionInfo();
			String cnntBSSID = null;
			String cnntSSID = null;
			if (connectInfo != null){
				cnntBSSID = connectInfo.getBSSID();
				cnntSSID = connectInfo.getSSID();
				Log.v(TAG, "已连接的wifi的唯一ID：" + connectInfo.getBSSID());
				Log.v(TAG, "已连接的wifi的SSID：" + connectInfo.getSSID());
			}
			for (int i = 0; i < size; i++) {
				map = new HashMap<String, Object>();
				scanResult = mScanResults.get(i);
				
				if (scanResult == null)
					continue;
				Log.v(TAG, "热点" + i + "的SSID:" + scanResult.SSID);
				//Log.v(TAG, "热点" + i + "的BSSID:" + scanResult.BSSID);
				map.put(WifiListViewAdapter.flag[0], scanResult.SSID);
				//用BSSID和SSID 唯一标识wifi网络
				if (connectInfo != null && cnntBSSID != null && cnntBSSID.equals(scanResult.BSSID) &&
						cnntSSID != null && cnntSSID.equals(scanResult.SSID)){
					map.put(WifiListViewAdapter.flag[1], "1");
					connectIndex = i;
				} else{
					map.put(WifiListViewAdapter.flag[1], "0");
				}
					
				/*if( scanResult != null && connectSSID != null && connectSSID.equals("\"" + scanResult.SSID + "\"") )
				{
					// 注意这里 从connectioninfo得到的ssid比从scan得到的ssid多了一个双引号
					map.put(WifiListViewAdapter.flag[1], "1");
					connectIndex = i;
				}else
				{
					map.put(WifiListViewAdapter.flag[1], "0");
				}*/
//				if( wifiManager.getConnectionInfo() != null && scanResult != null)
//				{
//						if (wifiManager.getConnectionInfo().getSSID().equals(scanResult.SSID)) {
//							if( conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
//							{
//								map.put(WifiListViewAdapter.flag[1], "1");
//								connectIndex = i;
//							}else
//								map.put(WifiListViewAdapter.flag[1], "0");
//						}else
//						{
//							map.put(WifiListViewAdapter.flag[1], "0");
//						}
//				}else
//				{
//					map.put(WifiListViewAdapter.flag[1], "0");
//				}
				map.put(WifiListViewAdapter.flag[2], wifiManager.calculateSignalLevel(scanResult.level, 4));
				if ( scanResult.capabilities.contains("PSK") || scanResult.capabilities.contains("EPA") )
				{
					map.put(WifiListViewAdapter.flag[5], 1);
				}else
				{
					map.put(WifiListViewAdapter.flag[5], 0);
				}
				mList.add(map);
			}
			wifiAdapter.notifyDataSetChanged();
		}
		
		
	}
	public void refreshWifiList()
	{
		
		ScanWifiThread();
		
	}
//	public static int calculateSignalLevel(int rssi, int numLevels) {
//        if (rssi <= MIN_RSSI) {
//            return 0;
//        } else if (rssi >= MAX_RSSI) {
//            return numLevels - 1;
//        } else {
//            int partitionSize = (MAX_RSSI - MIN_RSSI) / (numLevels - 1);
//            return (rssi - MIN_RSSI) / partitionSize;
//        }
//    }
	
	 // 指定配置好的网络进行连接  
    public void connectConfiguration(int index) { 
        // 索引大于配置好的网络索引返回  
        if (index > mWifiConfigurations.size()) { 
            return; 
        } 
        // 连接配置好的指定ID的网络  
        wifiManager.enableNetwork(mWifiConfigurations.get(index).networkId, 
                true); 
    } 
    
    WifiConfiguration CreateWifiInfo(String SSID, String Password, String mSecurity) 
    { 
    	//创建一个新的WifiConfiguration
    	WifiConfiguration wcg = new WifiConfiguration();
//    	wcg.b.BSSID = mBSSID;
    	//SSID和preSharedKey必须添加双引号，否则将会导致连接失败
    	wcg.SSID = "\"" + SSID + "\""; 
    	wcg.hiddenSSID = false;
    	wcg.status = WifiConfiguration.Status.ENABLED;
    	wcg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    	wcg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
    	wcg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    	wcg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    	wcg.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    	wcg.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    	//如果加密模式为WEP
    	if(mSecurity.equals("WEP"))
    	{ 
    	wcg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    	wcg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    	wcg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    	wcg.wepKeys[0] ="\"" + Password + "\""; //This is the WEP Password
    	wcg.wepTxKeyIndex = 0;
    	}
    	//如果加密模式为WPA EPA
    	else if(mSecurity.equals("WPA EAP"))
    	{
    	wcg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
    	wcg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    	wcg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    	wcg.preSharedKey = "\"" + Password+ "\"";
    	}
    	//如果加密模式为WPA PSK
    	else if(mSecurity.equals("WPA PSK"))
    	{
    	wcg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    	wcg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    	wcg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    	wcg.preSharedKey = "\"" + Password + "\"";
    	}
    	//无加密
    	else
    	{
    	wcg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    	}
    	return wcg;
    } 
    AlertDialog wifiAlertDialog;
    
    String ssid;
    int index;
    int ispw;
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
//			wifiManager.enableNetwork((Integer)mList.get(arg2).get("netid"), true);
			if (isConnecting){
				//Toast.makeText(WifiLoginActivity.this, "wifi正在连接，请稍候...", Toast.LENGTH_SHORT).show();
				toastTxt.setText("connecting wifi...");
				toast.setView(toastView);
				toast.show();
				return;
			}
			ssid = (String)mList.get(arg2).get("wifi");
			index = arg2;
			ispw = (Integer)mList.get(arg2).get("ispw");
			WifiConfiguration find = IsExsits( ssid );
			if( find == null )
			{
				passwordEt.setText("");
				wifiInputDialog.show();
				
				/*if( wifiAlertDialog == null )
				{
					wifiAlertDialog = new AlertDialog.Builder(WifiLoginActivity.this).setView(dialog_wifiView)
							.setNegativeButton("取消", null)
							.create();
				}
				if( ispw == 1 )
				{
					wifiAlertDialog.setMessage("配置" + ssid + " 的密码");
				}else
				{
					wifiAlertDialog.setMessage("该类型为无密码，按确定继续连接");
				}
					
				wifiAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						MobclickAgent.onEvent(mContext, "wifi_change");
						String pw = dialog_etPw.getText().toString().trim();
						if (pw.length() < 8){
							Toast.makeText(WifiLoginActivity.this, "WIFI密码不能少于8位！", 
									Toast.LENGTH_SHORT).show();
							toastTxt.setText("WIFI密码不能少于8位！");
							toast.setView(toastView);
							toast.show();
							dialog_etPw.setText("");
							return;
						}
						WifiConfiguration newWifiConfiguration ;
						if( ispw ==1 ){
							newWifiConfiguration = CreateWifiInfo(ssid, pw,  "WPA PSK");
						}else
						{
							newWifiConfiguration = CreateWifiInfo(ssid, pw,  "none");
						}
						int networkid = wifiManager.addNetwork(newWifiConfiguration);
						mList.get(index).put(WifiListViewAdapter.flag[4], networkid);
						boolean issave = wifiManager.saveConfiguration();
						boolean success = wifiManager.enableNetwork(networkid, true);
						if(success)
						{
							checkWifiStatus(index);
						}else{
							wifiManager.removeNetwork(networkid);
						}
						InputMethodManager imManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
						imManager.hideSoftInputFromWindow(dialog_etPw.getWindowToken(), 0);
						
					}
				});
				wifiAlertDialog.show();*/
			}else
			{
				if( "1".equals( mList.get(index).get(WifiListViewAdapter.flag[1])) )
				{
					//Toast.makeText(WifiLoginActivity.this, "已连接，如需更换wifi，直接选择其他wifi信号连接！", Toast.LENGTH_LONG).show();
					toastTxt.setText("connected！");
					toast.setView(toastView);
					toast.show();
				}else{
					//Toast.makeText(WifiLoginActivity.this, "正在发起连接", Toast.LENGTH_LONG).show();
					boolean success = wifiManager.enableNetwork(find.networkId, true);
					if(success)
					{
						checkWifiStatus(index);
					}else{
						wifiManager.removeNetwork(find.networkId);
					}
				}
			}
		}
	};
	
	protected void onStop() {
		super.onStop();
		WifiLoginActivity.this.finish();
	};
	public Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				isConnecting = false;
				if (wifiConnectDialog != null && wifiConnectDialog.isShowing())
					wifiConnectDialog.dismiss();
				if( conMan.getNetworkInfo(conMan.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED )
				{
					MainActivity.WIFI_STATE = 1; //设置状态为1表示wifi已连接
					if(connectIndex != -1)
					{
						mList.get(connectIndex).put(WifiListViewAdapter.flag[1], "0");
						connectIndex = -1;
					}
					mList.get(msg.arg1).put(WifiListViewAdapter.flag[1], "1");
					connectIndex = msg.arg1;
					wifiAdapter.notifyDataSetChanged();
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							WifiLoginActivity.this.finish();
						}
					},500);
				}else
				{
					MobclickAgent.onEvent(mContext, "wifi_wrong");
					if (flagCancelConnect){
						flagCancelConnect = false;
						//Toast.makeText(WifiLoginActivity.this, "连接已取消，请重新连接！", Toast.LENGTH_LONG).show();
						toastTxt.setText("disconnected!");
						toast.setView(toastView);
						toast.show();
					} else{
						//Toast.makeText(WifiLoginActivity.this, "连接失败可能信号不好或者密码错误造成的，请重试", Toast.LENGTH_LONG).show();
						toastTxt.setText("connecting failed!");
						toast.setView(toastView);
						toast.show();
					}
					WifiConfiguration configuration = IsExsits((String)mList.get(msg.arg1).get(WifiListViewAdapter.flag[0]));
					if( configuration != null )
					{
						wifiManager.removeNetwork(configuration.networkId);
					}
					dialog_etPw.setText("");
					
//					onItemClick(arg0, arg1, arg2, arg3);
				}
				break;
			case 1:
				mPbLoading.setVisibility(View.INVISIBLE);
				mBtnRefresh.setVisibility(View.VISIBLE);
				tv_wifistate.setText("");
				mList.clear();
				int size = mScanResults.size();
				HashMap<String, Object> map;
				ScanResult scanResult;
				
				//mList.clear();
				/*String connectSSID = null;
				if( wifiManager.getConnectionInfo() !=null )
				{
					connectSSID = wifiManager.getConnectionInfo().getSSID();
				}*/
				WifiInfo connectInfo = wifiManager.getConnectionInfo();
				String cnntBSSID = null;
				String cnntSSID = null;
				if (connectInfo != null){
					cnntBSSID = connectInfo.getBSSID();
					cnntSSID = connectInfo.getSSID();
					Log.v(TAG, "已连接的wifi的唯一ID：" + connectInfo.getBSSID());
					Log.v(TAG, "已连接的wifi的SSID：" + connectInfo.getSSID());
				}
				for (int i = 0; i < size; i++) {
					map = new HashMap<String, Object>();
					scanResult = mScanResults.get(i);
					
					if (scanResult == null)
						continue;
					Log.v(TAG, "热点" + i + "的SSID:" + scanResult.SSID);
					//Log.v(TAG, "热点" + i + "的BSSID:" + scanResult.BSSID);
					map.put(WifiListViewAdapter.flag[0], scanResult.SSID);
					//用BSSID和SSID 唯一标识wifi网络
					if (connectInfo != null && cnntBSSID != null && cnntBSSID.equals(scanResult.BSSID) &&
							cnntSSID != null && cnntSSID.equals(scanResult.SSID)){
						map.put(WifiListViewAdapter.flag[1], "1");
						connectIndex = i;
					} else{
						map.put(WifiListViewAdapter.flag[1], "0");
					}
						
					/*if( scanResult != null && connectSSID != null && connectSSID.equals("\"" + scanResult.SSID + "\"") )
					{
						// 注意这里 从connectioninfo得到的ssid比从scan得到的ssid多了一个双引号
						map.put(WifiListViewAdapter.flag[1], "1");
						connectIndex = i;
					}else
					{
						map.put(WifiListViewAdapter.flag[1], "0");
					}*/
//					if( wifiManager.getConnectionInfo() != null && scanResult != null)
//					{
//							if (wifiManager.getConnectionInfo().getSSID().equals(scanResult.SSID)) {
//								if( conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
//								{
//									map.put(WifiListViewAdapter.flag[1], "1");
//									connectIndex = i;
//								}else
//									map.put(WifiListViewAdapter.flag[1], "0");
//							}else
//							{
//								map.put(WifiListViewAdapter.flag[1], "0");
//							}
//					}else
//					{
//						map.put(WifiListViewAdapter.flag[1], "0");
//					}
					map.put(WifiListViewAdapter.flag[2], wifiManager.calculateSignalLevel(scanResult.level, 4));
					if ( scanResult.capabilities.contains("PSK") || scanResult.capabilities.contains("EPA") )
					{
						map.put(WifiListViewAdapter.flag[5], 1);
					}else
					{
						map.put(WifiListViewAdapter.flag[5], 0);
					}
					mList.add(map);
				}
				wifiAdapter.notifyDataSetChanged();
				break;
			case 2:
				toastTxt.setText("disconnected, try again!");
				toast.setView(toastView);
				toast.show();
				break;
			default:
				break;
			}
		};
	};
	
	public static boolean isConnecting = false;
	public static boolean flagCancelConnect = false;
	/**
	 * wifi连接提示框
	 */
	Dialog wifiConnectDialog = null;
	public void checkWifiStatus(final int index)
	{
		//progressDialog.show();
		if(connectIndex != -1 && connectIndex < mList.size())
		{
			mList.get(connectIndex).put(WifiListViewAdapter.flag[1], "0");
			connectIndex = -1;
		}
		wifiAdapter.notifyDataSetChanged();
		if (wifiConnectDialog == null){
			//wifiConnectDialog = new Dialog(mContext, R.style.FullHeightDialog);
			wifiConnectDialog = new CustomDialog(mContext, 370, 80, R.layout.initial,
					R.style.FullHeightDialog);
			//wifiConnectDialog.setMessage("正在连接，请稍候...");
			View view = getLayoutInflater().inflate(R.layout.initial, null);
			((TextView)view.findViewById(R.id.ini_txt)).setText("connecting...");
			wifiConnectDialog.setContentView(view);
			wifiConnectDialog.setCanceledOnTouchOutside(true);
		}
		wifiConnectDialog.show();
		isConnecting = true;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				NetworkInfo.State state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
				int checkCount = 0;
				//设置最多30秒等待
				while( state != NetworkInfo.State.CONNECTED && checkCount<50)
				{
					//By mouse
					if (wifiConnectDialog != null && !wifiConnectDialog.isShowing()){
						break;
					}
//					Message msg = handler.obtainMessage(1);
//					msg.obj =  conMan.getNetworkInfo(conMan.TYPE_WIFI).getDetailedState() ;
//					handler.sendMessage(msg);
					try {
						Thread.sleep(600);
						state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
						checkCount++;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (wifiConnectDialog != null && !wifiConnectDialog.isShowing() && 
						state != NetworkInfo.State.CONNECTED){
					flagCancelConnect = true;
				}
				Message msg = handler.obtainMessage(0);
				msg.arg1 = index;
				handler.sendMessage(msg);
				
			}
		}).start();
	}
//	public int findFromConfigue(String ssid)
//	{
//		int size = mWifiConfigurations.size();
//		for (int i = 0; i < size; i++) {
//			if( mWifiConfigurations.get(i).SSID.equals(ssid) )
//			{
//				return i;
//			}
//		}
//		return -1;
//	}
	public static final int TYPE_NO_PASSWD = 0x11;  
    public static final int TYPE_WEP = 0x12;  
    public static final int TYPE_WPA = 0x13;  
	OnClickListener buttonOnClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if ( v == mBtnRefresh ) {
				refreshWifiList();
			}else if( v== btn_close )
			{
				WifiLoginActivity.this.finish();
			}else if( v == btn_progress )
			{
				progressDialog.dismiss();
			}else if (v == cancelBtn) {
				if (wifiInputDialog != null && wifiInputDialog.isShowing()) {
					wifiInputDialog.dismiss();
				}
			}else if (v == okBtn) {
				MobclickAgent.onEvent(mContext, "wifi_change");
				String pw = passwordEt.getText().toString().trim();
				if (pw.length() < 8){
					toastTxt.setText("password can't be less than 8!");
					toast.setView(toastView);
					toast.show();
					passwordEt.setText("");
					return;
				}
				WifiConfiguration newWifiConfiguration ;
				if( ispw ==1 ){
					newWifiConfiguration = CreateWifiInfo(ssid, pw,  "WPA PSK");
				}else
				{
					newWifiConfiguration = CreateWifiInfo(ssid, pw,  "none");
				}
				int networkid = wifiManager.addNetwork(newWifiConfiguration);
				mList.get(index).put(WifiListViewAdapter.flag[4], networkid);
				boolean issave = wifiManager.saveConfiguration();
				boolean success = wifiManager.enableNetwork(networkid, true);
				if(success)
				{
					checkWifiStatus(index);
				}else{
					wifiManager.removeNetwork(networkid);
				}
				InputMethodManager imManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				imManager.hideSoftInputFromWindow(passwordEt.getWindowToken(), 0);
				wifiInputDialog.dismiss();
			}
		}
	};
	//定义几种加密方式，一种是WEP，一种是WPA，还有没有密码的情况  
    public enum WifiCipherType  
    {  
      WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID  
    }
    
    /**
     * 查看以前是否也配置过这个网络  
     * @param SSID
     * @return
     */
    private WifiConfiguration IsExsits(String SSID)  
    {  
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();  
           for (WifiConfiguration existingConfig : existingConfigs)   
           {  
             if (existingConfig.SSID.equals("\""+SSID+"\""))  
             {  
                 return existingConfig;  
             }  
           }  
        return null;   
    }  
    public void notifyWifiStateChange()
    {
    	int state = wifiManager.getWifiState();
    	switch (state) {
		case WifiManager.WIFI_STATE_ENABLING:
			tv_wifistate.setText("connecting...");
			break;
		case WifiManager.WIFI_STATE_ENABLED:
			tv_wifistate.setText("connecting...");
			//refreshWifiList();
			break;
		case WifiManager.WIFI_STATE_UNKNOWN:
			tv_wifistate.setText("connecting...");
			openWifi();
			break;
		case WifiManager.WIFI_STATE_DISABLING:
			tv_wifistate.setText("resetting...");
			break;
		case WifiManager.WIFI_STATE_DISABLED:
			wifiManager.setWifiEnabled(true);
			break;
		default:
//			tv_wifistate.setText("");
			break;
		}
    }
	public void notifyConnectChange() {
		// TODO Auto-generated method stub
		NetworkInfo.DetailedState state = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getDetailedState();
			String str_state = "";
			if( state == NetworkInfo.DetailedState.CONNECTED )
			{
				str_state = "已连接";
				if (progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				Toast.makeText(this, str_state, Toast.LENGTH_SHORT).show();
				return;
			}else if(  state == NetworkInfo.DetailedState.CONNECTING )
			{
				str_state = "正在连接...";
				if( mList.size() == 0 )
				{
//					refreshWifiList();
				}
			}else if(  state == NetworkInfo.DetailedState.BLOCKED )
			{
				str_state = "网络堵塞!";
			}else if(  state == NetworkInfo.DetailedState.AUTHENTICATING )
			{
				str_state = "正在认证...";
			}else if(  state == NetworkInfo.DetailedState.FAILED )
			{
				str_state = "连接失败！";
			}else if(  state == NetworkInfo.DetailedState.IDLE )
			{
				str_state = "正在准备数据连接配置...";
			}else if(  state == NetworkInfo.DetailedState.OBTAINING_IPADDR )
			{
				str_state = "正在获取IP地址...";
			}else if(  state == NetworkInfo.DetailedState.SUSPENDED )
			{
				str_state = "IP业务暂停！";
			}else if(  state == NetworkInfo.DetailedState.SCANNING )
			{
				str_state = "正在扫描...";
			}else if(  state == NetworkInfo.DetailedState.DISCONNECTING )
			{
				str_state = "正在断开当前连接...";
			}else if(  state == NetworkInfo.DetailedState.DISCONNECTED )
			{
//				str_state = "已关闭！";
				if( progressDialog.isShowing() )
				{
					progressDialog.dismiss();
				}
				if( connectIndex != -1)
				{
					if( mList.size() > connectIndex && mList.get(connectIndex).get(WifiListViewAdapter.flag[1]).equals("1"))
					{
						 mList.get(connectIndex).put(WifiListViewAdapter.flag[1],"0");
						 wifiAdapter.notifyDataSetChanged();
						 Toast.makeText(WifiLoginActivity.this, "Disconnected", Toast.LENGTH_LONG).show();
					}
				}
				
				return;
			}
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
//			progressDialog = new ProgressDialog(this);
//			progressDialog.setMessage(str_state);
			tv_progress.setText(str_state);
			progressDialog.show();
			
	}
}
